import { Component } from '@angular/core';
import {ActionSheetController, IonicPage, LoadingController, NavController, NavParams, Platform} from 'ionic-angular';
import {CommissionProvider} from "../../../providers/me/commission/commission";
import * as moment from 'moment';
import {File} from "@ionic-native/file";
import {FileOpener} from "@ionic-native/file-opener";
import {HttpEventType} from "@angular/common/http";
import {ToastService} from "../../../services/common/toast.service";
import {now} from "moment";
import {PermissionsService} from "../../../services/native/permissions/permissions.service";

/**
 * Generated class for the CommissionPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-commission',
  templateUrl: 'commission.html',
    providers: [CommissionProvider, File, FileOpener, ToastService, PermissionsService]
})
export class CommissionPage {

    // 时间插件--年月日汉字填充
    private pickerOptions = {
        cssClass: 'filter-add-picker'
    };

    sectionTime: any;
    time: any = '月中';
    minTime: any;
    maxTime: any;

    moment = moment;

    yearList:any[]=[];

  constructor(public navCtrl: NavController,
              public actionSheetCtrl: ActionSheetController,
              private commissionProvider: CommissionProvider,
              private file: File,
              private fileOpener: FileOpener,
              private loadingCtrl: LoadingController,
              private toastService: ToastService,
              private platform: Platform,
              private permissionsService: PermissionsService,
              public navParams: NavParams) {

      let nowTime = new Date();

      this.sectionTime = nowTime.toISOString();
      // this.minTime = nowTime.setFullYear(nowTime.getFullYear()-1);
      this.minTime = new Date((new Date(this.sectionTime).getFullYear()-1)+'/'+(new Date(this.sectionTime).getMonth()+3)+'/01 00:00:00').toISOString();
      this.maxTime = nowTime.toISOString();

      this.yearList.push((new Date(this.sectionTime).getFullYear()-1));
      this.yearList.push(nowTime.getFullYear());
  }

  ionViewDidLoad() {

  }

    openAttachFile() {
        if(this.platform.is('android')) {
            this.permissionsService.checkAndroidStoragePermission().then(res => {
                if (res == 'GRANTED') {
                    this.createPDF();
                } else if (res == 'DENIED') {
                    this.toastService.showToast('请到“设置>应用”中启用“存储”权限');
                    return;
                }
            }).catch(e => {
                console.log('检查存储权限异常',e);
            })
        } else {
            this.createPDF();
        }
    }

    /**
     * 生成PDF
     */
    createPDF() {
        console.log('生成PDF');
        let now = 0;
        let loading = this.loadingCtrl.create({
            spinner: 'circles',
            content: '文件加载中：0%',
            dismissOnPageChange: false,
            enableBackdropDismiss: true
        });
        loading.onDidDismiss(() => {
            // console.log('on did dissmisse');
            // this.fileService.abort();
            return;
        });
        loading.present();

        let mTimer = setInterval(() => {
            loading.setContent('文件加载中: ' + Math.floor(now) + '%');
            if (now >= 99) {
                clearInterval(mTimer);
            }
        }, 300);

        let nYear = new Date(this.sectionTime).getFullYear();
        let nMonth= new Date(this.sectionTime).getMonth()+1;
        console.log(nYear);
        console.log(nMonth);
        let nSectionTime = new Date(nYear+'/'+nMonth+'/01 00:00:00');
        this.commissionProvider.getCommissionPDF(moment(nSectionTime).unix(), this.time == '月中'? 'M' : 'E')
            .subscribe(res => {
                console.log(res);
                if (res.type === HttpEventType.DownloadProgress) {
                    now = res.loaded / res.total * 100;
                }

                if (res.type === HttpEventType.UploadProgress) {
                    console.log("Upload progress event");
                }

                if (res.type === HttpEventType.Response) {
                    console.log("response received...", res.body);
                    loading.dismiss();
                    if ((res.body as Blob).size == 0) {
                        // this.toastService.showToast('暂无文件');
                        this.toastService.showToast('文件打开失败');
                        return;
                    }

                    setTimeout(() => {
                        this.file.writeFile(this.file.dataDirectory, '我的收入.pdf', res.body as Blob, {replace: true}).then(result => {
                            console.log(result.toURL());
                            this.fileOpener.open(decodeURI(result.toURL()), 'application/pdf')
                                .then(() => console.log('File is opened'))
                                .catch(e => {
                                    console.log('open file catch:',e);
                                    if (e.message.indexOf('No Activity found to handle Intent') > -1) {
                                        if (e.message.indexOf('application/pdf') > -1) {
                                            this.toastService.showToast('请至应用商店下载安装PDF阅读器');
                                            loading.dismiss();
                                            return;
                                        }
                                    }

                                    this.toastService.showToast('文件打开失败');
                                    loading.dismiss();
                                });
                        }).catch(e => {
                            this.toastService.showToast('文件加载失败，请稍后重试');
                            loading.dismiss();
                        });
                    },300);

                    // this.file.writeFile(this.file.dataDirectory, '我的收入.pdf', res.body as Blob, {replace: true}).then(result => {
                    //     console.log(result.toURL());
                    //     this.fileOpener.open(decodeURI(result.toURL()), 'application/pdf')
                    //         .then(() => console.log('File is opened'))
                    //         .catch(e => {
                    //             if (e.message.indexOf('No Activity found to handle Intent') > -1) {
                    //                 if (e.message.indexOf('application/pdf') > -1) {
                    //                     this.toastService.showToast('请至应用商店下载安装PDF阅读器');
                    //                     loading.dismiss();
                    //                     return;
                    //                 }
                    //             }
                    //
                    //             this.toastService.showToast('文件打开失败');
                    //             loading.dismiss();
                    //         });
                    // }).catch(e => {
                    //     this.toastService.showToast('文件加载失败，请稍后重试');
                    //     loading.dismiss();
                    // });
                }
            }, error2 => {
                // this.toastService.showToast('文件传输失败');
                // this.toastService.showToast('啊哦，服务器开小差了，请稍后重试');
                loading.dismiss();
            });
    }

    showActionSheet() {
        let actionSheet = this.actionSheetCtrl.create({
            title:'时间',
            buttons: [
                {
                    text: '月中',
                    cssClass: this.time=='月中'?'action-sheet-selected':null,
                    handler: () => {
                        this.time='月中';
                    }
                },{
                    text: '月末',
                    cssClass: this.time=='月末'?'action-sheet-selected':null,
                    handler: () => {
                        this.time = '月末';
                    }
                },{
                    text: '取消',
                    role: 'cancel'
                }
            ]
        });
        actionSheet.present();
    }

    /**
     * 后退
     */
    goBack() {
        this.navCtrl.pop();
    }

}
